package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.entity.SysUser;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.dto.DeviceDetailVo;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.IotMsgNotifyData;
import com.zzyl.nursing.vo.IotMsgService;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-23
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IDeviceDataService deviceDataService;

    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备信息
     *
     * @param device 设备信息
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        // 更新数据库
        this.updateById(device);

        // 更新IOT

        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        // 设置设备名称
        body.withDeviceName(device.getDeviceName());
        body.withDescription(device.getNickname());


        request.withBody(body);

        try {
            UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
            if (updateDeviceResponse.getHttpStatusCode() == HttpStatus.HTTP_OK) {
                return 1;
            } else {
                return 0;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 批量删除设备信息
     *
     * @param ids 需要删除的设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息信息
     *
     * @param id 设备信息主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品
     */
    @Override
    public void syncProductList() {
        try {
            //对接华为云API，获取产品列表
            ListProductsResponse response = client.listProducts(new ListProductsRequest());
            if (response.getHttpStatusCode() != HttpStatus.HTTP_OK) {
                throw new BaseException("同步产品列表异常");
            }
            //获取响应结果的产品列表
            List<ProductSummary> products = response.getProducts();
            if (CollUtil.isNotEmpty(products)) {
                //转换为json
                String jsonStr = JSONUtil.toJsonStr(products);
                //存入redis
                redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, jsonStr);
            }

        } catch (BaseException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询全部产品
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis查询
        String s = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StrUtil.isBlank(s)) {
            return Collections.emptyList();
        }
        //转换数据
        List<ProductSummary> list = JSONUtil.toList(s, ProductSummary.class);
        //转换成vo
        List<ProductVo> collect = list.stream().map(x -> ProductVo.builder().productKey(x.getProductId()).productName(x.getName()).build()).collect(Collectors.toList());

        return collect;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        //判断名称是否重复
        Long countbyname = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (countbyname > 0) {
            throw new BaseException("设备名称重复");
        }

        //判断标识是否重复,根据雪花id
        String nodeid = IdUtil.getSnowflakeNextIdStr();

        //判断同一位置是否绑定过同样设备
        Long countbylocation = this.lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if (countbylocation > 0) {
            throw new BaseException("不要绑定同样设备");
        }
        //注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setNodeId(nodeid);
        addDevice.setDeviceName(dto.getDeviceName());
        addDevice.setDescription(dto.getNickname());
        addDevice.setProductId(dto.getProductKey());
        //设备密钥
        String secret = IdUtil.fastSimpleUUID();
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);

        addDeviceRequest.setBody(addDevice);


        try {
            AddDeviceResponse response = client.addDevice(addDeviceRequest);
            if (response.getHttpStatusCode() != HttpStatus.HTTP_CREATED) {
                throw new BaseException("注册失败");
            }

            String iotid = response.getDeviceId();

            //设备表新增数据
            Device bean = BeanUtil.toBean(dto, Device.class);
            bean.setIotId(iotid);
            bean.setNodeId(nodeid);
            bean.setSecret(secret);
            bean.setHaveEntranceGuard(dto.getNickname().contains("门禁") ? 1 : 0);

            String productid = dto.getProductKey();
            String getproductnamefromcache = getproductnamefromcache(productid);
            if (StrUtil.isNotBlank(getproductnamefromcache)) {
                bean.setProductName(getproductnamefromcache);
            }
            this.save(bean);


        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("注册失败");
        }
    }

    /**
     * 查询设备详细数据
     *
     * @param dto
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(DeviceDto dto) {
        String productKey = dto.getProductKey();
        String iotId = dto.getIotId();
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId)
                .eq(Device::getProductKey, productKey)
                .one();
        if (device == null) {
            throw new BaseException("表中设备不存在");
        }
        //查询华为云数据
        ShowDeviceRequest showDeviceRequest = new ShowDeviceRequest();
        showDeviceRequest.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(showDeviceRequest);
        if (response.getHttpStatusCode() != HttpStatus.HTTP_OK) {
            throw new BaseException("IOT设备不存在");
        }
        //合并数据
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        vo.setGmtCreate(device.getCreateTime());
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());
        vo.setDeviceSecret(device.getSecret());
        Long l = Long.valueOf(device.getCreateBy());
        SysUser sysUser = sysUserService.selectUserById(l);
        vo.setCreator(sysUser.getUserName());
        vo.setDeviceStatus(response.getStatus());
        vo.setFirmwareVersion(response.getFwVersion());
        String activeTime = response.getActiveTime();
        if (StrUtil.isNotBlank(activeTime)) {
            LocalDateTime localDateTime = OffsetDateTime.parse(activeTime)
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setGmtActive(localDateTime);
        }

        return vo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //参数校验
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }

        JSONObject productModelInfo = null;

        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilityList = response.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilityList)) {
            productModelInfo = JSONUtil.parseObj(serviceCapabilityList.get(0));
        }
        return productModelInfo;
    }

    /**
     * 1.7 查询指定设备的物模型运行状态
     *
     * @param deviceName
     * @param productKey
     * @return
     */
    @Override
    public Map<String, Object> queryDevicePropertyStatus(String deviceName, String productKey) {
        //查询数据
        Device device = this.lambdaQuery().eq(Device::getDeviceName, deviceName)
                .eq(Device::getProductKey, productKey)
                .one();
        if (device == null) {
            throw new BaseException("没有设备");
        }

        ShowDeviceShadowRequest req = new ShowDeviceShadowRequest();
        //根据id查询数据
        req.setDeviceId(device.getIotId());


        ShowDeviceShadowResponse showDeviceShadowResponse = client.showDeviceShadow(req);
        if (showDeviceShadowResponse.getHttpStatusCode() != HttpStatus.HTTP_OK) {
            throw new BaseException("查询失败");
        }

        List<DeviceShadowData> shadow = showDeviceShadowResponse.getShadow();
        if (CollUtil.isNotEmpty(shadow)) {
            List<Map<String, Object>> propertyStatusInfoList = new ArrayList<>();
            String eventTime = shadow.get(0).getReported().getEventTime();
            LocalDateTime reportTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();


            JSONObject entries = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
            entries.forEach((k, v) -> {
                Map<String, Object> map = new HashMap<>();
                map.put("identifier", k);
                map.put("value", v);
                map.put("time", reportTime);
                propertyStatusInfoList.add(map);
            });

            Map<String, Object> propertyStatusInfoMap = new HashMap<>();
            propertyStatusInfoMap.put("propertyStatusInfo", propertyStatusInfoList);

            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("list", propertyStatusInfoMap);

            return resultMap;

        }


        return null;
    }

    /**
     * 删除设备
     *
     * @param device 要删除的设备信息
     */
    @Override
    public void deletedevice(Device device) {
        // 删除数据库
        Device device1 = this.lambdaQuery().eq(Device::getIotId, device.getIotId())
                .eq(Device::getProductKey, device.getProductKey())
                .one();
        if (device1 != null) {
            this.removeById(device1.getId());
        } else {
            throw new BaseException("数据库删除失败");
        }

        // 删除云端
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();
        deleteDeviceRequest.withDeviceId(device.getIotId()); // 设置设备ID

        try {
            DeleteDeviceResponse deleteDeviceResponse = client.deleteDevice(deleteDeviceRequest);
            if (deleteDeviceResponse.getHttpStatusCode() != HttpStatus.HTTP_NO_CONTENT) {
                throw new BaseException("删除云端设备失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("删除云端设备异常：" + e.getMessage());
        }
    }

    private String getproductnamefromcache(String productId) {

        String json = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        List<ProductSummary> list = JSONUtil.toList(json, ProductSummary.class);
        ProductSummary productSummary = list.stream().filter(x -> productId.equals(x.getProductId())).findFirst().get();
        if (productSummary != null) {
            return productSummary.getName();//产品名
        }
        return null;
    }

    /**
     * 基于IOT设备上传通知的数据，批量保存设备数据
     *
     * @param notifyData
     */
    @Override
    public void saveBatchData(IotMsgNotifyData notifyData) {
        //1. 判断设备是否存在
        String deviceId = notifyData.getHeader().getDeviceId();
        Device device = this.lambdaQuery().eq(Device::getIotId, deviceId)
                .one();
        if (device == null) {
            throw new BaseException("设备不存在");
        }
        //2. 获取上报的服务信息
        List<IotMsgService> serviceList = notifyData.getBody().getServices();

        serviceList.forEach(x -> {
            //3. 获取上报的物模型数据信息
            Map<String, Object> properties = x.getProperties();
            String eventTime = x.getEventTime(); //数据上报时间，时间格式：20251025T021057Z
            LocalDateTime alertTime = OffsetDateTime.parse(eventTime, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX"))
                    .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            List<DeviceData> deviceDataList = properties.entrySet().stream().map(entry -> {
                String functionId = entry.getKey();
                Object dataValue = entry.getValue();
                DeviceData deviceData = DeviceData.builder()
                        .deviceName(device.getDeviceName())//设备名
                        .iotId(deviceId)//设备id
                        .nodeId(device.getNodeId())//节点id
                        .nickname(device.getNickname())//设备昵称
                        .productKey(device.getProductKey())//产品key
                        .productName(device.getProductName())//产品名
                        .functionId(functionId)
                        .dataValue(String.valueOf(dataValue))
                        .accessLocation(device.getBindingLocation())//绑定位置
                        .locationType(device.getLocationType())//位置类型
                        .physicalLocationType(device.getPhysicalLocationType())//物理位置
                        .alarmTime(alertTime) //数据上报时间
                        .build();
                return deviceData;
            }).collect(Collectors.toList());

//            List<DeviceData> deviceDataList = new ArrayList<>();
//            properties.forEach((k,v)->{
//                String functionId = k;//功能名（设备的物模型属性名）
//                Object dataValue = v; //属性上报的值
//
//                DeviceData deviceData = DeviceData.builder()
//                        .deviceName(device.getDeviceName())//设备名
//                        .iotId(deviceId)//设备id
//                        .nodeId(device.getNodeId())//节点id
//                        .nickname(device.getNickname())//设备昵称
//                        .productKey(device.getProductKey())//产品key
//                        .productName(device.getProductName())//产品名
//                        .functionId(functionId)
//                        .dataValue(String.valueOf(dataValue))
//                        .accessLocation(device.getBindingLocation())//绑定位置
//                        .locationType(device.getLocationType())//位置类型
//                        .physicalLocationType(device.getPhysicalLocationType())//物理位置
//                        .alarmTime(alertTime) //数据上报时间
//                        .build();
//                deviceDataList.add(deviceData);
//            });

            //4. 批量新增设备数据
            deviceDataService.saveBatch(deviceDataList);
            // 存入到redis  key：hash数据类型（大key，小key,  value）iot:device_last_data   iot_id
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,deviceId,JSONUtil.toJsonStr(deviceDataList));
        });


    }
}
